<?php
/**
 * This file is part of the Agora distribution. 
 * Detailed copyright and licensing information can be found
 * in the gpl-3.0.txt file which should be included in the distribution.
 * 
 * @version		$Id: 3.0.14 Olympus 2010-09-28 rammstein4o $
 * @copyright  2007 - 2010 jVitals
 * @license   GPLv3 Open Source
 * @link       http://jvitals.com
 * @since      File available since initial release
 */

class AParserHelper {
    function handle_img_tag($url, $width, $height)  {
        // TODO - need to determine the diff between post image and sig image.
		$url_orig = $url;
		
		// show bigger image in post if needed
		if (!$this->agora_config['o_uploadile_thumb']) {
			$url = str_replace('mini_','',$url);
		// show thumb in post - if thumb doesn't exists, show bigger image
		} else {
			$url = !file_exists(str_replace(str_replace('www.', '', JURI::root()),JPATH_BASE . DS, str_replace('www.', '', $url))) ? str_replace('mini_','',$url) : $url;
		}
		
        $url2 = str_replace('mini_','',$url_orig);
		
        if (!$this->enable_img) {
		
            $target = ($this->agora_config['o_new_window_link'] == 1) ? ' target="_blank"' : '';
            $img_tag = "<a href=\"$url\"$target >&lt;".Agora::lang('Image link')."&gt;</a>";
			
        } else {
		
            if ($width != '' || $height != '') {
                $size = " $width $height";
            } else {
                $size = '';
            }
			
			// attachments must open in lightbox, image links - open in new link
            if (strpos(str_replace('www.', '', $url), str_replace('www.', '', JURI::root())) === false) {
				$rel = '';
				$target = ($this->agora_config['o_new_window_link'] == 1) ? ' target="_blank"' : '';
            } else {
				$rel = 'lightbox-postImg';
				$target = '';
            }

						$target = trim($target);
            //!!! - this is a quick and dirty change - should be dilimited by post id
            //$img_tag = "<a href=\"$url2\" rel=\"lightbox-postImg\"><img$size class=\"ag_postimage\" src=\"$url\" alt=\"".htmlspecialchars($url)."\" height=\"100\"/></a>";
            //$img_tag = "<img$size class=\"ag_postimage\" src=\"$url\" alt=\"".htmlspecialchars($url)."\" height=\"100\"/>";
            $img_tag = "<a href=\"$url2\" $target rel=\"$rel\"><img$size class=\"ag_postimage\" src=\"$url\" alt=\"".htmlspecialchars($url)."\" /></a>"; // removed 'height'
        }

        return $img_tag;
    }

    function handle_img_tag_inurl($url, $width, $height)  {
	
		// show bigger image in post if needed
		if (!$this->agora_config['o_uploadile_thumb']) {
			$url = str_replace('mini_','',$url);
		// show thumb in post - if thumb doesn't exists, show bigger image
		} else {
			$url = !file_exists(str_replace(str_replace('www.', '', JURI::root()),JPATH_BASE . DS, str_replace('www.', '', $url))) ? str_replace('mini_','',$url) : $url;
		}
		
        if (!$this->enable_img) {
            $img_tag = "&lt;".Agora::lang('Image link')."&gt;";
        } else {
            if ($width != '' || $height != '') {
                $size = " $width $height";
            } else {
                $size = '';
            }
            $img_tag = "<img$size class=\"ag_postimage\" src=\"$url\" alt=\"".htmlspecialchars($url)."\" />";
        }

        return $img_tag;
    }

	function handle_url_tag($url, $link = '') {
		if (strpos($link, '[img]') === false) {
			return $this->handle_url_tag_noimg($url, $link);
		} else {
			return $this->handle_url_tag_img($url, $link);
		}
	}

    function handle_url_tag_img($url, $link = '') {
        $full_url = str_replace(array(' ', '\'', '`', '"'), array('%20', '', '', ''), $url);
        if (strpos($url, 'www.') === 0) { // If it starts with www, we add http://
			$full_url = 'http://'.$full_url;
        } else if (strpos($url, 'ftp.') === 0) { // Else if it starts with ftp, we add ftp://
			$full_url = 'ftp://'.$full_url;
        } else if (!preg_match('#^([a-z0-9]{3,6})://#', $url, $bah)) { // Else if it doesn't start with abcdef://, we add http://
			$full_url = 'http://'.$full_url;
		}
		$full_url = str_replace('mini_','',$full_url);
        if (!$this->enable_img) {
            $target = ($this->agora_config['o_new_window_link'] == 1) ? ' target="_blank"' : '';
        } else {
			// attachments must open in lightbox, image links - open in new link
            if (strpos(str_replace('www.', '', $full_url), str_replace('www.', '', JURI::root())) === false) {
				$rel = '';
				$target = ($this->agora_config['o_new_window_link'] == 1) ? ' target="_blank"' : '';
            } else {
				$rel = 'lightbox-postImg';
				$target = '';
            }
        }
		
        $target = trim($target);
		$link = preg_replace('#\[img\s*(width=\d+\w*)?\s*(height=\d+\w*)?\s*\]((ht|f)tps?://)([^\s<"]*?)\[/img\]#e', '$this->handle_img_tag_inurl(\'$3$5\',\'$1\',\'$2\')', $link);

        // This is the original to follow links Edited by Hazzaa
        return "<a href=\"$full_url\" $target rel=\"$rel\">$link</a>";
    }

    function handle_url_tag_noimg($url, $link = '') {
        $full_url = str_replace(array(' ', '\'', '`', '"'), array('%20', '', '', ''), $url);
        if (strpos($url, 'www.') === 0) { // If it starts with www, we add http://
			$full_url = 'http://'.$full_url;
        } else if (strpos($url, 'ftp.') === 0) { // Else if it starts with ftp, we add ftp://
			$full_url = 'ftp://'.$full_url;
        } else if (!preg_match('#^([a-z0-9]{3,6})://#', $url, $bah)) { // Else if it doesn't start with abcdef://, we add http://
			$full_url = 'http://'.$full_url;
		}
		
        // Ok, not very pretty :-)
        $link = ($link == '' || $link == $url) ? ((strlen($url) > 55) ? substr($url, 0 , 39).' &hellip; '.substr($url, -10) : $url) : stripslashes($link);

        // This is the original to follow links Edited by Hazzaa
        $target = ($this->agora_config['o_new_window_link'] == 1) ? ' target="_blank"' : '';
        // Hide Links From Guests 1.0
        return "<a href=\"$full_url\"$target>$link</a>";
    }

	function censor($text) {
		static $search_for, $replace_with;
		// If not already built in a previous call, build an array of censor words and their replacement text
		if (!isset($search_for)) {
			$censor_model = & Model::getInstance('CensoringModel');
			$words = $censor_model->loadAll();

			$search_for = array();
			$replace_with = array();
			foreach ($words as $pair) {
				$replace_with[] = $pair['replace_with'];
				$search_for[] = '/\b('.str_replace('\*', '\w*?', preg_quote($pair['search_for'], '/')).')\b/i';
			}
		}
		if (!empty($search_for))
			$text = substr(preg_replace($search_for, $replace_with, ' '.$text.' '), 1, -1);
		return $text;

	}

    function parseMessage($text, $hide_smilies) {
        $text = AString::escape($text);

		if ($this->agora_config['o_censoring'])
			$text = $this->censor($text);

		$show_smilies = $this->agora_config['o_smilies'] && $this->agora_user['show_smilies'] && (int)$hide_smilies == 0;

        if ($this->agora_config['p_message_bbcode'] == '1' && strpos($text, '[') !== false && strpos($text, ']') !== false)
        {
            $this->enable_img = intval($this->agora_config['p_message_img_tag']) && intval($this->agora_user['show_img']);
            $text = $this->fix_broken_bbcode($text);
            $text = $this->bbcode($text, $show_smilies);
        } else {
	        if ($this->agora_config['o_make_links']) {
		        $text = $this->links($text);
			}

			if ($show_smilies) {
	            $text = $this->smilies($text);
	        }
		}
		$rand = rand();
		
		$text = str_replace(array('lightbox-postImg', '&#91;', '&#93;', '&amp;#91;', '&amp;#93;'), array('lightbox-postImg-'.$rand, '[', ']', '[', ']'), $text);
        return $this->cleanup($text);
    }

    function parseSignature($text) {
        $text = AString::escape($text);

		if ($this->agora_config['o_censoring'])
			$text = $this->censor($text);

		$show_smilies = $this->agora_config['o_smilies_sig'] && $this->agora_user['show_smilies'];

        if ($this->agora_config['p_sig_bbcode'] == '1' && strpos($text, '[') !== false && strpos($text, ']') !== false) {
			if ((int)$this->agora_user['is_guest']) {
				$this->agora_user['show_img_sig'] = 1;
			}
            $this->enable_img = intval($this->agora_config['p_sig_img_tag']) && intval($this->agora_user['show_img_sig']);
            $text = $this->bbcode($text, $show_smilies);
        } else {
			if ($this->agora_config['o_make_links']) {
			    $text = $this->links($text);
		    }

	        if ($show_smilies) {
		        $text = $this->smilies($text);
	        }
		}
		$rand = rand();
		$text = str_replace('lightbox-postImg', 'lightbox-postImg-sig-'.$rand, $text);
        return $this->cleanup($text);
    }

    function smilies($text)
    {
        static $smiley_text, $smiley_img;

        if (!isset($smiley_text)) {
            $model = & Model::getInstance('SmiliesModel');
            $smilies = $model->loadAll();

            $smiley_text = array();
            $smiley_img = array();

            foreach ($smilies as $db_smilies)
            {
                $smiley_text_array = array($db_smilies['text']);
                $smiley_text = array_merge($smiley_text, $smiley_text_array);

                $smiley_img_array = array($db_smilies['image']);
                $smiley_img = array_merge($smiley_img, $smiley_img_array);
            }

        }

        $text = ' '.$text.' ';

        $num_smilies = count($smiley_text);
        for ($i = 0; $i < $num_smilies; ++$i)
        $text = preg_replace("#(?<=.\W|\W.|^\W)".preg_quote($smiley_text[$i], '#')."(?=.\W|\W.|\W$)#m", '$1<img src="'.Agora::image('smilies/'.$smiley_img[$i]).'"  alt="'.substr($smiley_img[$i], 0, strrpos($smiley_img[$i], '.')).'" />$2', $text);

        return substr($text, 1, -1);
    }

    function cleanup($text)
    {
        $space_pattern = array("\n", "\t", '  ', '  ','<p></p>');
        $space_replace = array('<br />', '&nbsp; &nbsp; ', '&nbsp; ', ' &nbsp;','');
        $text = str_replace($space_pattern, $space_replace, $text);
        //return '<p>'.$text.'</p>';

		/*** emailcloak (joomla plugin) ***/
		global $mainframe;
		$plugin 		= &JPluginHelper::getPlugin('content', 'emailcloak');
		$pluginParams 	= new JParameter($plugin->params);
		require_once JPATH_SITE . DS . 'plugins' . DS . 'content' . DS . 'emailcloak.php';

		$row = new stdClass;
		$row->text = $text;

		plgContentEmailCloak($row, $pluginParams);

		return '<p>' . $row->text . '</p>';
    }
	
	function handle_raw_url($link) {
		
		$linkarr = explode(',',$link);
		$link = $linkarr[0];
		$suffix = '';
		if (count($linkarr) > 1) {
			array_shift($linkarr);
			$suffix = ',' . implode(',', $linkarr);
		}
		return $this->handle_url_tag($link) . $suffix;
	}

    function links($text) {
		$text = ' '.$text;

		//~ $text = preg_replace('#([\s\(\)])(https?|ftp|news){1}://([\w\-]+\.([\w\-]+\.)*[\w]+(:[0-9]+)?(/[^"\s\(\)<\[]*)?)#ie', '\'$1\'.$this->handle_url_tag(\'$2://$3\')', $text);
		//~ $text = preg_replace('#([\s\(\)])(www|ftp)\.(([\w\-]+\.)*[\w]+(:[0-9]+)?(/[^"\s\(\)<\[]*)?)#ie', '\'$1\'.$this->handle_url_tag(\'$2.$3\', \'$2.$3\')', $text);
		
	//	$text = preg_replace('#([\s\(\)])(https?|ftp|news){1}://([\w\-]+\.([\w\-]+\.)*[\w]+(:[0-9]+)?\S+(/[^"\s\(\)<\[]*)?)#ie', '\'$1\'.$this->handle_raw_url(\'$2://$3\')', $text);
//		$text = preg_replace('#([\s\(\)\]\>])(https?|ftp|news){1}://([\d\w\-]+\.(?:[\d\w\-]+\.)*[\w]+(?::[0-9]+)?)/?((?:[^"\s\(\)<\[]*)?)#ie', '\'$1\'.$this->handle_raw_url(\'$2://$3/$4\')', $text);
		$rep = '(https?|ftp|news){1}://([\d\w\-]+\.(?:[\d\w\-]+\.)*[\w]+(?::[0-9]+)?)/?((?:[^"\s\(\)<\[]*)?)';
		$text = preg_replace('#([^\]\=\"\'\>])' . $rep . '#ie', '\'$1\'.$this->handle_raw_url(\'$2://$3/$4\')', $text);
		$text = preg_replace('#(\[li\])' . $rep . '#ie', '\'$1\'.$this->handle_raw_url(\'$2://$3/$4\')', $text);
		//~ $text = preg_replace('#((mailto\:|(news|(ht|f)tp(s?))\://){1}\S+)#ie', '$this->handle_raw_url(\'$1\')', $text);
		return $text;
    }

    function split_text($text, $start, $end)
    {
        $tokens = explode($start, $text);

        $outside[] = $tokens[0];

        $num_tokens = count($tokens);
        for ($i = 1; $i < $num_tokens; ++$i)
        {
            $temp = explode($end, $tokens[$i]);
            $inside[] = $temp[0];
            $outside[] = $temp[1];
        }

        if ($this->agora_config['o_indent_num_spaces'] != 8 && $start == '[code]')
        {
            $spaces = str_repeat(' ', $this->agora_config['o_indent_num_spaces']);
            $inside = str_replace("\t", $spaces, $inside);
        }

        return array($inside, $outside);
    }
	
	function fix_broken_bbcode($text) {
		$code_patterns = array(
			array('open' => '[quot', 'close' => '[/quot', 'open_fill' => '[quote]', 'close_fill' => '[/quote]'),
			array('open' => '[QUOT', 'close' => '[/QUOT', 'open_fill' => '[QUOTE]', 'close_fill' => '[/QUOTE]'),
		);
		
		$new = $text;
		
		foreach ($code_patterns as $code) {
			// count opening and closing tags and determine how much are unmatched
			$open_cnt = substr_count($new,$code['open']);
			$close_cnt = substr_count($new,$code['close']);	
			$unmatched_cnt = ($close_cnt - $open_cnt);
			$diff = 0;
			if ($unmatched_cnt > 0) {
				$diff = 1;
			}
			if ($unmatched_cnt < 0) {
				$diff = -1;
			}
			$unmatched_cnt = abs($unmatched_cnt);
			
			// if unmatched found - fill with closing or opening tags
			if ($diff != 0) {
				$code_pos = $diff > 0 ? strpos($new,$code['open']) : strrpos($new,$code['close']) ;
				$fill = $diff > 0 ? $code['open_fill'] : $code['close_fill'] ;
				
				if ($code_pos) {
					$new = substr($new,0,($code_pos)) . str_repeat($fill,$unmatched_cnt) . substr($new,$code_pos);
				} else {
					$new = $diff > 0 ? $fill . $new : $new . $fill ;
				}

			}

		}
		
		$pattern = array('#\\[quote author=(.*?) link(.*?)\](.*?)\[/QUOTE\]#is');
		$replace = array('[quote=$1]$3[/quote]');
		$new = preg_replace($pattern, $replace, $new);
		
		return $new;
	}

    function bbcode($text, $show_smilies, $for_email=false)
    {
        static $replace, $pattern, $code_pattern, $code_replace;


        if (stripos($text, '[CODE]') !== false && stripos($text, '[/CODE]') !== false)
        {

            $text = str_ireplace("[CODE]", "[code]", $text);
            $text = str_ireplace("[/CODE]", "[/code]",$text);
            if (strpos($text, '[code]') !== false && strpos($text, '[/code]') !== false)
            {
                list($inside, $outside) = $this->split_text($text, '[code]', '[/code]');
                $outside = array_map('ltrim', $outside);
                $text = implode('<">', $outside);
            }
        }


        if (!isset($replace) || !isset($pattern)) {
			$bbvideo_width = $this->agora_config['o_bbcode_video_width'];
			$bbvideo_height = $this->agora_config['o_bbcode_video_height'];

			if ($for_email)
				include(AGORA_PATH.DS.'include'.DS.'parser_patterns_for_email.php');
			else
            include(AGORA_PATH.DS.'include'.DS.'parser_patterns.php');
        }

        if ($this->agora_config['o_make_links']) {
            $text = $this->links($text);
        }

        if ($show_smilies) {
            $text = $this->smilies($text);
        }

        if (stripos($text, 'QUOTE') !== false)
        {

            $text = str_replace("[QUOTE]", "[quote]", $text);
            $text = str_replace("[/QUOTE]", "[/quote]",$text);
            $text = str_replace('[quote]', '</p><blockquote><div class="incqbox">', $text);
            $text = preg_replace('#\[quote=(&quot;|"|\'|)(.*)\\1\]#seU', '"</p><blockquote><div class=\"incqbox\"><h4>".str_replace(array(\'[\', \'\\"\'), array(\'&#91;\', \'"\'), \'$2\')." ".Agora::lang(\'wrote\').":</h4>"', $text);
            $text = preg_replace('#\[\/quote\]\s*#', '</div></blockquote><p>', $text);

        }

        if (stripos($text, 'SPOILER') !== false)
        {
            $text = str_ireplace("[SPOILER]", "[spoiler]", $text);
            $text = str_ireplace("[/SPOILER]", "[/spoiler]",$text);

            if (strpos($text, 'spoiler') !== false)
            {
                $text = str_replace('[spoiler]', '<div class="slideContainer"><div class="toolbar">&nbsp;'.Agora::lang('Spoiler').'&nbsp;<a href="javascript:void(0);" class="ShowHidden"><img src="'.Agora::image('icons/downarrow.png').'" border="0" alt="Show Spoiler"/></a>&nbsp;<a href="javascript:void(0);" class="HideHidden"><img src="'.Agora::image('icons/uparrow.png').'" border="0" alt="Hide Spoiler" /></a></div><div class="SlideText">'.""."&nbsp;", $text);

                $text = preg_replace('#\[\/spoiler\]\s*#', "</div></div>", $text);
            }
        }

        if (strpos($text, 'hide') !== false)
        {
          $user = JFactory::getUser();

          if ($user->guest)
          {
            $text = preg_replace("#\[hide\](.+?)\[/hide\]#is", '<h4 class="HideText">['.Agora::lang('Hidden text - guest user').']</h4>', $text);
          }
          else
          {
            $text = str_replace('[hide]', '<blockquote class="HideText"><h4>'.Agora::lang('Hidden text').':</h4>', $text);
            $text = preg_replace('#\[\/hide\]\s*#', '</blockquote>', $text);
          }
        }

        if (strpos($text, 'IMG') !== false)
        {
            $text = str_replace("[IMG", "[img", $text);
            $text = str_replace("[/IMG]", "[/img]",$text);
        }
        
        // remove whitespace from between table tags because nl2br messes it up
        if (false !== stripos($text, '[table]')) {
        	$text = preg_replace('#(\[(?:table|\/caption)\])[^\[]*?\[#i', '$1[', $text);
        	$text = preg_replace('#(\[tr\])[^\[]*?(\[t(?:h|d))#i', '$1$2', $text);
        	$text = preg_replace('#(\[\/t)(h|d)(\])[^\[]*?(\[t)(\2)#i', '$1$2$3$4$5', $text);
        	$text = preg_replace('#(\[\/t(?:h|d|r)\])[^\[]*?\[#i', '$1[', $text);
        	$text = preg_replace('#(\[\/tr\])[^\[]*?(\[tr)#i', '$1$2', $text);
        }
        // whitespace fix for lists
        if (false !== stripos($text, '[li]')) {
        	$text = preg_replace('#(\[(?:o|u)l\])[^\[]*?\[#i', '$1[', $text);
        	$text = preg_replace('#(\[\/li\])[^\[]*?(\[(?:(?:o|u)l|li))#i', '$1$2', $text);
        }

        $upattern = $this->capitalizeArray($pattern);

        $text = preg_replace($upattern, $replace, $text);

        $text = preg_replace($pattern, $replace, $text);


        if (isset($inside))
        {
            $outside = explode('<">', $text);
            $text = '';

            $num_tokens = count($outside);

            for ($i = 0; $i < $num_tokens; ++$i)
            {
                $text .= $outside[$i];
                if (isset($inside[$i]))
                {
                    $num_lines = ((substr_count($inside[$i], "\n")) + 3) * 1.5;
                    $height_str = ($num_lines > 35) ? '35em' : $num_lines.'em';
                    $text .= '</p><div class="ag_codebox"><div class="ag_incqbox"><h4>'.Agora::lang('Code').':</h4><div class="ag_scrollbox"><pre>'.$inside[$i].'</pre></div></div></div><p>';
                }
            }
        }

        return $text;
    }



    function capitalizeArray($array) {

        foreach($array as $item)
        {
            $item = strtoupper($item);
            $newworkdata[] = str_replace("#S", "#s", str_replace("#E", "#e", $item));

        }
        return $newworkdata;
    }

}
